import { useState, useEffect, FC } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { IconCaretRight } from '@arco-design/web-react/icon';
import { getTrainRanking } from '@/api/train';

// 图片资源
import NO1 from '@/assets/AiImgs/NO1.png';
import NO2 from '@/assets/AiImgs/NO2.png';
import NO3 from '@/assets/AiImgs/NO3.png';
import './index.less';

// 类型定义
interface PageDetail {
  training_id: number;
}

interface Trainee {
  trainee_id: number;
  rank: number;
  name: string;
  id: number | string;
  score: number;
}

interface RankingListProps {
  pageDetail?: PageDetail;
}

const RankingList: FC<RankingListProps> = ({ pageDetail }) => {
  const { training_id } = pageDetail || {};
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const picid = searchParams.get('prcid');
  const [rankList, setRankList] = useState<Trainee[]>([]);

  // 获取排行榜数据
  useEffect(() => {
    if (!training_id) return;
    
    const fetchRanking = async () => {
      try {
        const res = await getTrainRanking(training_id);
        if (res.code === 2000) {
          setRankList(res.data?.list || []);
        }
      } catch (error) {
        console.error('Failed to fetch training ranking:', error);
      }
    };

    fetchRanking();
  }, [training_id]);

  // 导航到学习页面
  const goToPage = (trainee_id: number) => {
    navigate(`/ToStudy?trainee_id=${trainee_id}&picid=${picid}`, { replace: false });
  };

  // 获取排名图标
  const getRankIcon = (rank: number) => {
    switch(rank) {
      case 1: return <img src={NO1} alt="第一名" className="w-6 h-6" />;
      case 2: return <img src={NO2} alt="第二名" className="w-6 h-6" />;
      case 3: return <img src={NO3} alt="第三名" className="w-6 h-6" />;
      default: 
        return (
          <div className="w-6 h-6 rounded-full bg-gray-100 flex items-center justify-center text-gray-800">
            {rank}
          </div>
        );
    }
  };

  return (
    <div className="px-6 overflow-x-auto bg-white max-h-[78vh] overflow-y-auto rounded-tl-2xl scorePage">
      {rankList.length > 0 ? (
        rankList.map((trainee) => (
          <div 
            key={trainee.trainee_id} 
            className="flex items-center justify-between py-4 border-b border-[#EBEBEB]"
          >
            <div className="flex items-center justify-start">
              <div className="mr-7">
                {getRankIcon(trainee.rank)}
              </div>
              
              <div className="text-gray-900 font-medium w-32 mr-5 truncate">
                {trainee.name} ({trainee.id})
              </div>
              
              <div className="mr-7">
                <span className={`
                  font-bold text-lg relative
                  ${trainee.score === 100 ? 'BottomLineWidth' : ''}
                  borderBottomLineScore
                `} style={{ fontFamily: 'SpeedeeApp-BoldItalic' }}>
                  <span className="relative z-10">{trainee.score}</span>
                </span>
                <span className="text-gray-900 text-base ml-1">分</span>
              </div>
            </div>
            
            <div>
              <button 
                onClick={() => goToPage(trainee.trainee_id)}
                className="text-gray-600 hover:text-gray-900 text-xs flex items-center"
              >
                去学习 <IconCaretRight className="text-red-600 ml-1" />
              </button>
            </div>
          </div>
        ))
      ) : (
        <div className="py-8 text-center text-gray-500">
          暂无排行榜数据
        </div>
      )}
    </div>
  );
};

export default RankingList;